<template>
  <div class="exam-management-page">
    <!-- 顶部信息栏 -->
    <div class="top-info">
      <span>培训班编号：{{ trainingClassCode || "123456" }}</span>
      <span>培训班名称：{{ className || "XXX" }}</span>
      <span>姓名：{{ name || "张三" }}</span>
      <span>证件编号：{{ idCard || "123456789123456789" }}</span>
    </div>

    <!-- 搜索区域 -->
    <el-form :inline="true" :model="searchForm" class="search-form" label-width="80px">
      <el-form-item label="是否通过">
        <el-select v-model="searchForm.isPass" placeholder="选择是否通过">
          <el-option label="全部" value="" />
          <el-option label="通过" value="通过" />
          <el-option label="未通过" value="未通过" />
        </el-select>
      </el-form-item>
      <el-form-item label="考试状态">
        <el-select v-model="searchForm.examStatus" placeholder="选择考试状态">
          <el-option label="全部" value="" />
          <el-option label="已考试" value="已考试" />
          <el-option label="考试中" value="考试中" />
          <el-option label="未考试" value="未考试" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮栏 -->
    <div class="operation-buttons">
      <el-button type="primary" plain>导出</el-button>
      <el-button
        type="primary"
        plain
        @click="openRemarkDialog"
        :disabled="!selection || selection.length === 0"
      >
        学员备注
      </el-button>
      <el-button
        type="primary"
        plain
        @click="openNoticeDialog"
        :disabled="!selection || selection.length === 0"
      >
        学员通知
      </el-button>
      <el-button
        type="primary"
        plain
        @click="handleMakeupExam"
        :disabled="!selection || selection.length === 0"
      >
        多次补考
      </el-button>
      <el-button
        type="primary"
        plain
        @click="handleQuestionDetail"
        :disabled="!selection || selection.length !== 1"
      >
        考题详情
      </el-button>
    </div>

    <!-- 考试记录表格 -->
    <el-table
      :data="tableData"
      border
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <!-- <el-table-column prop="id" label="编号" width="80" /> -->
      <el-table-column prop="name" label="姓名" width="80" />
      <el-table-column prop="idCard" label="证件编号" width="180" />
      <el-table-column prop="gender" label="性别" width="60" />
      <el-table-column prop="phone" label="电话" width="120" />
      <el-table-column prop="company" label="单位名称" width="120" />
      <el-table-column prop="examStartTime" label="考试开始时间" width="150" />
      <el-table-column prop="examDuration" label="考试时长" width="80" />
      <el-table-column prop="examWays" label="考试途径" width="80" />
      <el-table-column prop="examScore" label="考试成绩" width="80" />
      <el-table-column prop="isPass" label="是否通过" width="80">
        <template #default="scope">
          <span :style="{ color: scope.row.isPass === '通过' ? 'green' : 'red' }">
            {{ scope.row.isPass }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="examStatus" label="考试状态" width="80" />
      <el-table-column prop="makeupExam" label="补考情况" width="80" />
      <el-table-column prop="makeupMark" label="补考标记" width="80" />
      <el-table-column prop="remark" label="备注" width="120" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button type="text" @click="handleQuestionDetail(scope.row)">考题详情</el-button>
          <el-button type="text" @click="openRemarkDialog(scope.row)">备注</el-button>
          <el-button type="text" @click="openNoticeDialog(scope.row)">学员通知</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      />
    </div>

    <!-- 学员通知弹窗（移植完整功能） -->
    <el-dialog
      title="发送学员通知"
      :visible.sync="noticeDialogVisible"
      width="50%"
      :before-close="handleNoticeDialogClose"
    >
      <el-form :model="noticeForm" ref="noticeForm" :rules="noticeRules">
        <!-- 新增：通知类型（短信/门户） -->
        <el-form-item label="通知类型" prop="sendTypes">
          <el-checkbox-group v-model="noticeForm.sendTypes">
            <el-checkbox label="0" style="margin-right: 20px">短信</el-checkbox>
            <el-checkbox label="1">门户</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="通知标题" prop="title">
          <el-input v-model="noticeForm.title" placeholder="请输入通知标题"></el-input>
        </el-form-item>
        <el-form-item label="通知内容" prop="content">
          <el-input
            type="textarea"
            v-model="noticeForm.content"
            placeholder="请输入通知内容"
            rows="6"
            maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="发送范围">
          <el-radio-group v-model="noticeForm.range" @change="handleRangeChange">
            <el-radio label="all">所有学员</el-radio>
            <el-radio label="scheduled">已安排的学员</el-radio>
            <el-radio label="selected">指定学员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="noticeForm.range === 'selected'"
          class="selected-users-form-item"
          prop="selectedUsers"
        >
          <el-select
            v-model="noticeForm.selectedUsers"
            multiple
            placeholder="请输入学员姓名搜索并选择"
            filterable
            remote
            :remote-method="queryUsers"
            :loading="userLoading"
            style="width: 100%;"
            clearable
            @clear="handleSelectClear"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            >
              <span style="float: left">{{ user.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                身份证号：{{ user.idCard || '无证件号' }}
              </span>
            </el-option>
            <template #empty>
              <div style="text-align: center; color: #909399;">
                {{ userLoading ? '搜索中...' : '无匹配学员，请更换关键词' }}
              </div>
            </template>
          </el-select>
          <div class="selected-count" v-if="noticeForm.range === 'selected'">
            已选择 {{ noticeForm.selectedUsers.length }} 名学员
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="noticeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitNotice" :loading="noticeLoading">发送</el-button>
      </div>
    </el-dialog>

    <!-- 学员备注弹窗（移植完整功能） -->
    <el-dialog
      :title="remarkDialogTitle"
      :visible.sync="remarkDialogVisible"
      width="60%"
      size="mini"
      @close="resetRemarkForm"
    >
      <el-form
        ref="remarkForm"
        :model="remarkForm"
        label-width="80px"
        :rules="remarkRules"
        class="remark-form"
      >
        <el-form-item label="备注内容" prop="remarks">
          <el-input
            v-model="remarkForm.remarks"
            type="textarea"
            :rows="4"
            placeholder="请输入备注内容"
            style="width: 100%"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>
        <!-- 新增：备注历史记录 -->
        <el-form-item label="备注历史" label-width="80px">
          <el-table
            :data="remarkHistory"
            border
            stripe
            size="mini"
            :cell-style="{ 'vertical-align': 'middle' }"
            style="width: 100%;"
            :loading="remarkLoading"
            empty-text="暂无备注记录"
          >
            <el-table-column prop="time" label="时间" align="center" width="180" />
            <el-table-column prop="operator" label="备注人" align="center" width="120" />
            <el-table-column prop="content" label="备注" align="left" />
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="mini" @click="remarkDialogVisible = false">取消</el-button>
          <el-button size="mini" type="primary" @click="submitRemark" :loading="remarkSubmitting">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 多次补考弹窗 -->
    <el-dialog
      title="多次补考设置"
      :visible.sync="makeupExamDialogVisible"
      width="600px"
      @close="handleCloseMakeupExam"
    >
      <div class="selected-students">
        <h4>已选择学员（{{ selection.length }}人）</h4>
        <el-tag
          v-for="student in selection"
          :key="student.id"
          closable
          @close="removeStudent(student.id)"
          style="margin-right: 5px; margin-bottom: 5px;"
        >
          {{ student.name }}（{{ student.id }}）
        </el-tag>
      </div>
      <el-form :model="makeupExamForm" :rules="makeupExamRules" ref="makeupExamFormRef" label-width="120px">
        <el-form-item label="允许补考次数" prop="makeupTimes">
          <el-input v-model.number="makeupExamForm.makeupTimes" type="number" placeholder="请输入允许的补考次数" />
        </el-form-item>
        <el-form-item label="补考时间范围" prop="makeupTimeRange">
          <el-date-picker
            v-model="makeupExamForm.makeupTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="是否自动安排补考" prop="autoMakeup" label-width="150px">
          <el-radio-group v-model="makeupExamForm.autoMakeup">
            <el-radio label="是" />
            <el-radio label="否" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="补考备注" label-width="150px">
          <el-input v-model="makeupExamForm.remark" type="textarea" rows="3" placeholder="请输入补考相关备注" />
        </el-form-item>

        <div style="text-align: center; margin-top: 20px;">
          <el-button @click="makeupExamDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitMakeupExam">确定</el-button>
        </div>
      </el-form>
    </el-dialog>

    <!-- 试题详情弹窗 -->
    <el-dialog
      :title="currentStudent.name ? `${currentStudent.name}的试题详情` : '试题详情'"
      :visible.sync="examPaperDialogVisible"
      width="800px"
      @close="handleCloseQuestionDetail"
    >
      <div class="exam-paper-container">
      <!-- <div class="paper-header">
        <div class="paper-info">
          <p>考试编号: {{ currentExamPaper.examNo }}</p>
          <p>考试日期: {{ currentExamPaper.examDate }}</p>
          <p>总分: {{ currentExamPaper.score }}</p>
        </div>
      </div> -->

      <div class="questions-container">
        <div
          class="question-item"
          v-for="(question, index) in currentExamPaper.questions"
          :key="question.questionId"
        >
          <div class="question-header">
            <span class="question-index">{{ index + 1 }}.</span>
            <span class="question-type">
              {{ getQuestionType(question.questionType) }}
            </span>
          </div>
          <div class="question-content">
            {{ question.questionName }}
          </div>

          <!-- 选项展示 -->
          <div v-if="question.questionOptionList && question.questionOptionList.length > 0" class="question-options">
            <div
              class="option-item"
              v-for="option in question.questionOptionList"
              :key="option.optionId"
              :class="{
                'correct-option': option.optionName === question.answer,
                'student-option': option.optionName === question.studentAnswer
              }"
            >
              <span class="option-label">{{ option.optionName }}.</span>
              <span class="option-content">{{ option.optionContent }}</span>
            </div>
          </div>

          <!-- 答案和解析 -->
          <div class="question-answer">
            <div class="answer-label">参考答案: {{ question.answer || '无' }}</div>
            <div v-if="question.studentAnswer" class="student-answer">
              你的答案: {{ question.studentAnswer }}
            </div>
            <div v-if="question.analysisContent" class="answer-analysis">
              解析: {{ question.analysisContent }}
            </div>
          </div>
        </div>
      </div>
    </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="examPaperDialogVisible = false">取消</el-button>
        <el-button type="primary">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入所需API（移植功能+列表接口）
import { getExamListByClassId ,getExamList,getExamRecordInfo} from "@/api/examination/examRecord";
import { listRemarksByParams, addRemarks } from "@/api/training/remarks";
import { studentNoticeProcess } from "@/api/training/studentNotice.js";

export default {
  name: "ExamManagement",
  data() {
    return {
      // 新增考卷弹窗相关数据
      examPaperDialogVisible: false,
      currentExamPaper: {
        examNo: '',
        examDate: '',
        score: '',
        questions: []
      },
      // 父组件参数
      classId: "",
      className: "",
      name: "", // 用于getList的studentName参数
      idCard: "", // 用于getList的idNumber参数（修正用户笔误的IdCard）
      trainingClassCode: "",
      studentId: "",
      projectId: "",

      // 搜索与表格数据
      selection: [],
      searchForm: { isPass: "", examStatus: "" }, // 仅含考试状态、是否通过筛选
      tableData: [], // 接口返回后填充，清空默认模拟数据
      pagination: { currentPage: 1, pageSize: 10, total: 0 },
      allUsers: [], // 存储所有学员数据，用于通知弹窗搜索

      // 学员通知（移植完整字段+状态）
      noticeDialogVisible: false,
      noticeLoading: false, // 发送加载状态
      noticeForm: {
        title: "",
        content: "",
        range: "all",
        selectedUsers: [],
        sendTypes: [] // 新增：0=短信，1=门户（移植核心字段）
      },
      noticeRules: {
        sendTypes: [{ required: true, message: "请选择通知类型", trigger: "change" }], // 新增：类型必填
        title: [{ required: true, message: "请输入通知标题", trigger: "blur" }],
        content: [
          { required: true, message: "请输入通知内容", trigger: "blur" },
          { max: 500, message: "内容不能超过500个字符", trigger: "blur" }
        ],
        selectedUsers: [{ required: true, message: "请选择学员", trigger: "change" }] // 选中学员必填
      },
      userLoading: false,
      userOptions: [], // 搜索结果展示列表

      // 学员备注（移植完整字段+状态）
      remarkDialogVisible: false,
      remarkDialogTitle: "学员备注",
      remarkForm: { remarks: "", studentId: null }, // 新增：关联学员ID
      remarkHistory: [], // 接口返回后填充，清空默认模拟数据
      remarkLoading: false, // 历史加载状态
      remarkSubmitting: false, // 提交加载状态
      remarkRules: {
        remarks: [{ required: true, message: "请输入备注内容", trigger: "blur" }]
      },
      userFlagId: null, // 当前登录用户ID（从store获取，用于备注操作）

      // 多次补考（新增：选中学员移除功能）
      makeupExamDialogVisible: false,
      makeupExamForm: {
        makeupTimes: 1,
        makeupTimeRange: [],
        autoMakeup: "否",
        remark: "",
      },
      makeupExamRules: {
        makeupTimes: [{ required: true, message: "请输入允许的补考次数", trigger: "blur" }],
        makeupTimeRange: [{ required: true, message: "请选择补考时间范围", trigger: "change" }],
        autoMakeup: [{ required: true, message: "请选择是否自动安排补考", trigger: "change" }],
      },

      // 试题详情（新增：当前查看学员）
      currentStudent: {},
      questionData: {
        singleChoice: [
          {
            question: "XXXX",
            options: [
              { content: "XXXX", isSelected: false, isCorrect: false },
              { content: "XXXX", isSelected: false, isCorrect: false },
              { content: "XXXX", isSelected: true, isCorrect: false },
              { content: "XXXX", isSelected: false, isCorrect: true },
            ],
            userAnswer: "C",
            correctAnswer: "D",
            isCorrect: false,
          },
          {
            question: "XXXX",
            options: [
              { content: "XXXX", isSelected: false, isCorrect: false },
              { content: "XXXX", isSelected: false, isCorrect: false },
              { content: "XXXX", isSelected: true, isCorrect: true },
              { content: "XXXX", isSelected: false, isCorrect: false },
            ],
            userAnswer: "C",
            correctAnswer: "C",
            isCorrect: true,
          },
        ],
        multipleChoice: [
          {
            question: "XXXX",
            options: [
              { content: "XXXX", isSelected: true, isCorrect: false },
              { content: "XXXX", isSelected: false, isCorrect: true },
              { content: "XXXX", isSelected: true, isCorrect: false },
              { content: "XXXX", isSelected: false, isCorrect: false },
            ],
            userAnswer: "AC",
            correctAnswer: "BC",
            isCorrect: false,
          },
          {
            question: "XXXX",
            options: [
              { content: "XXXX", isSelected: true, isCorrect: true },
              { content: "XXXX", isSelected: true, isCorrect: true },
              { content: "XXXX", isSelected: true, isCorrect: true },
              { content: "XXXX", isSelected: false, isCorrect: false },
            ],
            userAnswer: "ABC",
            correctAnswer: "ABC",
            isCorrect: true,
          },
        ],
        judgment: [
          {
            question: "XXXX",
            userAnswer: "对",
            correctAnswer: "错",
            isCorrect: false,
          },
          {
            question: "XXXX",
            userAnswer: "对",
            correctAnswer: "对",
            isCorrect: true,
          },
        ],
      },
    };
  },
  watch: {
    '$route.query.classId': {
      immediate: true,
      handler(newId) {
        const params = this.$route.params;
        this.classId = params.classId;
        this.trainingClassCode = params.trainingClassCode;
        this.className = params.className;
        this.name = params.name; // 从路由参数获取学员姓名
        this.idCard = params.idCard; // 从路由参数获取证件号
        this.projectId = params.projectId;
        this.studentId = params.studentId;
        console.log(params)
        this.getList(); // 路由参数变化后加载列表
      }
    }
  },
  created() {
    // 获取当前登录用户ID（用于备注操作的身份标识）
    this.userFlagId = this.$store?.state?.user?.id || "admin";
  },
  methods: {
    // ---------------------- 核心：实现getList接口调用 ----------------------
    async getList() {
      try {
        // 接口参数：按要求映射（trainingClassId=classId，studentName=name，idNumber=idCard）
        const res = await getExamList({
          trainingClassId: this.classId, // 培训班ID（父组件参数）
          projectId: this.projectId,
          studentId: this.studentId,
          studentName: this.name, // 学员姓名（父组件参数）
          idNumber: this.idCard, // 证件编号（父组件参数，修正笔误IdCard）
          examStatus: this.searchForm.examStatus, // 考试状态（搜索框参数）
          examResult: this.searchForm.isPass, // 是否通过（搜索框参数）
          pageNum: this.pagination.currentPage, // 页码
          pageSize: this.pagination.pageSize // 每页条数
        });

        if (res.code !== 200 || !Array.isArray(res.rows)) {
          this.$message.error("考试记录加载失败，请重试");
          return;
        }

        // 格式化表格数据（与table列prop匹配）
        this.tableData = res.rows.map(item => ({
          id: item.studentId || "-",
          name: item.studentName || "-",
          idCard: item.idNumber || "-",
          gender: item.sex || "-",
          phone: item.phonenumber || "-",
          company: item.unitName || "-",
          examStartTime: item.examStartTime || "-",
          examDuration: item.examDuration ? `${item.examDuration}分钟` : "-",
          examWays: item.examPathway === "0" ? "手机" : item.examPathway === "1" ? "电脑" : "-",
          examScore: item.totalScore || "-",
          isPass: item.examResult || "-",
          examStatus: item.examStatus || "-",
          makeupExam: item.makeUpStatus || "-",
          makeupMark: item.makeUpMark || "-",
          remark: item.examRecordRemark || "-",
          item:item
        }));

        // 更新分页总数
        this.pagination.total = res.total || 0;

        // 初始化：所有学员数据（用于通知弹窗的搜索）
        this.allUsers = [...this.tableData];
        this.userOptions = this.tableData.map(u => ({
          id: u.id,
          name: u.name,
          idCard: u.idCard // 携带证件号用于搜索结果展示
        }));

      } catch (error) {
        this.$message.error("接口请求失败，请检查网络");
        console.error("getExamListByClassId错误:", error);
      }
    },

    // ---------------------- 搜索与分页 ----------------------
    handleSearch() {
      this.pagination.currentPage = 1; // 搜索重置到第一页
      this.getList();
    },
    handleReset() {
      this.searchForm = { isPass: "", examStatus: "" }; // 重置搜索条件
      this.pagination.currentPage = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getList();
    },
    handleSelectionChange(selection) {
      this.selection = selection;
    },

    // ---------------------- 移植：学员通知完整功能 ----------------------
    openNoticeDialog(row) {
      this.initNoticeForm(); // 初始化表单
      this.noticeDialogVisible = true;

      // 若从表格行点击，默认选中当前学员
      if (row && row.id) {
        this.noticeForm.range = "selected";
        this.noticeForm.selectedUsers = [row.id];
      }
    },
    // 初始化通知表单（重置状态+清除校验）
    initNoticeForm() {
      this.noticeForm = {
        title: "",
        content: "",
        range: "all",
        selectedUsers: [],
        sendTypes: []
      };
      this.noticeLoading = false;
      this.$nextTick(() => {
        if (this.$refs.noticeForm) this.$refs.noticeForm.clearValidate();
      });
    },
    // 发送范围切换（全部/已安排/指定）
    handleRangeChange(newRange) {
      if (newRange === "all") {
        // 全部学员：默认选中所有学员ID
        this.noticeForm.selectedUsers = this.allUsers.map(user => user.id);
      } else if (newRange === "scheduled") {
        // 已安排学员：筛选出有考试记录的学员（可根据实际业务调整）
        this.noticeForm.selectedUsers = this.allUsers
          .filter(user => user.examStatus !== "未考试")
          .map(user => user.id);
      } else {
        // 指定学员：清空选中
        this.noticeForm.selectedUsers = [];
      }
      // 清除选中学员的校验状态
      this.$nextTick(() => {
        if (this.$refs.noticeForm) this.$refs.noticeForm.clearValidate("selectedUsers");
      });
    },
    // 清空选中学员
    handleSelectClear() {
      this.noticeForm.selectedUsers = [];
    },
    // 远程搜索学员（按姓名/证件号匹配）
    queryUsers(query) {
      if (!query) {
        this.userOptions = [...this.allUsers];
        return;
      }
      this.userLoading = true;
      // 模拟接口延迟（实际项目可去掉setTimeout）
      setTimeout(() => {
        this.userOptions = this.allUsers.filter(user =>
          user.name.includes(query) || user.idCard.includes(query)
        );
        this.userLoading = false;
      }, 300);
    },
    // 提交通知（调用移植API）
    async submitNotice() {
      this.$refs.noticeForm.validate(async valid => {
        if (!valid) return;

        this.noticeLoading = true;
        try {
          const params = {
            sendType: this.noticeForm.range, // 发送范围（all/scheduled/selected）
            studentIds: this.noticeForm.selectedUsers, // 选中学员ID列表
            isSms: this.noticeForm.sendTypes.includes("0") ? "1" : "0", // 是否短信
            isPortal: this.noticeForm.sendTypes.includes("1") ? "1" : "0", // 是否门户
            noticeTitle: this.noticeForm.title,
            noticeContent: this.noticeForm.content,
            sendTime: new Date().toLocaleString("zh-CN", {
              year: "numeric", month: "2-digit", day: "2-digit",
              hour: "2-digit", minute: "2-digit", second: "2-digit",
              hour12: false
            }).replace(/\//g, "-"),
            trainingClassId: this.classId // 关联当前培训班
          };

          const res = await studentNoticeProcess(params);
          if (res.code === 200) {
            this.$message.success("通知发送成功");
            this.noticeDialogVisible = false;
          } else {
            this.$message.error(res.msg || "通知发送失败");
          }
        } catch (err) {
          this.$message.error("通知接口调用失败：" + (err.msg || err.message));
        } finally {
          this.noticeLoading = false;
        }
      });
    },
    // 关闭通知弹窗（重置表单）
    handleNoticeDialogClose() {
      this.noticeDialogVisible = false;
      this.initNoticeForm();
    },

    // ---------------------- 移植：学员备注完整功能 ----------------------
    openRemarkDialog(row) {
      // 优先获取行数据，无则取选中数据（需选中1个学员）
      let targetRow = row;
      if (!targetRow || !targetRow.id) {
        if (!this.selection || this.selection.length !== 1) {
          return this.$message.warning("请选择单个学员添加备注");
        }
        targetRow = this.selection[0];
      }

      // 关联学员ID+设置标题
      this.remarkForm.studentId = targetRow.id;
      this.remarkDialogTitle = `学员【${targetRow.name}】备注`;
      this.remarkLoading = true;

      // 加载备注历史（调用移植API）
      this.loadRemarkHistory();
    },
    // 加载备注历史（调用listRemarksByParams API）
    async loadRemarkHistory() {
      try {
        const res = await listRemarksByParams({
          foreignId: this.remarkForm.studentId, // 学员ID
          remarkType: "4" // 备注类型：学员备注（与培训班页面一致）
        });

        // 格式化历史数据
        this.remarkHistory = res.rows.map(item => ({
          time: item.createTime || "-",
          operator: item.createBy || "未知用户",
          content: item.remarks || "-"
        }));
      } catch (err) {
        this.$message.error("加载备注历史失败：" + (err.msg || err.message));
        this.remarkHistory = [];
      } finally {
        this.remarkLoading = false;
        this.remarkDialogVisible = true;
      }
    },
    // 重置备注表单（关闭弹窗后调用）
    resetRemarkForm() {
      this.$nextTick(() => {
        if (this.$refs.remarkForm) this.$refs.remarkForm.resetFields();
        this.remarkForm = { remarks: "", studentId: null };
      });
    },
    // 提交备注（调用addRemarks API）
    async submitRemark() {
      this.$refs.remarkForm.validate(async valid => {
        if (!valid) return;

        this.remarkSubmitting = true;
        try {
          const res = await addRemarks({
            foreignId: this.remarkForm.studentId, // 学员ID
            remarkType: "4", // 学员备注类型
            remarks: this.remarkForm.remarks, // 备注内容
            createBy: this.userFlagId // 当前登录用户ID
          });

          if (res.code === 200) {
            this.$message.success("备注提交成功");
            this.remarkDialogVisible = false;
            this.getList(); // 刷新表格，展示最新备注
          } else {
            this.$message.error(res.msg || "备注提交失败");
          }
        } catch (err) {
          this.$message.error("备注接口调用失败：" + (err.msg || err.message));
        } finally {
          this.remarkSubmitting = false;
        }
      });
    },

    // ---------------------- 多次补考（新增：选中学员移除） ----------------------
    handleMakeupExam() {
      if (!this.selection || this.selection.length === 0) {
        return this.$message.warning("请选择需要补考的学员");
      }
      this.makeupExamDialogVisible = true;
    },
    // 移除选中的补考学员
    removeStudent(id) {
      this.selection = this.selection.filter(student => student.id !== id);
    },
    handleCloseMakeupExam() {
      this.makeupExamDialogVisible = false;
      this.$refs.makeupExamFormRef.resetFields();
    },
    handleSubmitMakeupExam() {
      this.$refs.makeupExamFormRef.validate((valid) => {
        if (valid) {
          console.log("补考设置提交：", this.makeupExamForm);
          console.log("补考学员：", this.selection);
          this.$message.success("补考设置提交成功");
          this.makeupExamDialogVisible = false;
        }
      });
    },

    // ---------------------- 试题详情 ----------------------
    async handleQuestionDetail(row) {
      // 优先获取行数据，无则取选中数据
      if (row && row.id) {
        this.currentStudent = { ...row };
      } else {
        if (!this.selection || this.selection.length !== 1) {
          return this.$message.warning("请选择单个学员查看试题详情");
        }
        this.currentStudent = { ...this.selection[0] };
      }
      this.examPaperDialogVisible = true;
      const res = await getExamRecordInfo({
          studentId: this.currentStudent.id,
          trainingClassId: this.classId,
          examRecordId:this.currentStudent.item.examRecordId
        });
        // 处理外层考试记录数据
          let  examRecords = res.rows.map(record => ({
            // 保存原始记录数据，用于查看考卷
            originalRecord: record
          }));
          let record=examRecords[0]
      // 实际项目可在此处调用接口加载该学员的试题数据：this.loadQuestionData(this.currentStudent.id)
      this.currentExamPaper = {
        examNo: record.examNo,
        examDate: record.examDate,
        score: record.score,
        questions: record.originalRecord.examRecordInfoDtoList || []
      };
    },
    // 辅助方法：获取考试状态文本
    getExamStatus(examResult, theoryResult) {
      // 优先使用整体考试结果
      if (examResult === '通过' || examResult === '0') return '通过';
      if (examResult === '未通过' || examResult === '1') return '未通过';

      // 没有整体结果时使用理论考试结果
      if (theoryResult === '0') return '通过';
      if (theoryResult === '1') return '未通过';

      // 其他状态
      return '待评价';
    },

    // 辅助方法：获取题目类型文本
    getQuestionType(type) {
      const typeMap = {
        '1': '单选题',
        '2': '多选题',
        '3': '判断题'
      };
      return typeMap[type] || `题型${type}`;
    },
    handleCloseQuestionDetail() {
      this.examPaperDialogVisible = false;
      this.currentStudent = {};
    }
  },
};
</script>

<style scoped>
.exam-management-page {
  padding: 10px;
  background-color: #fff;
  min-height: calc(100vh - 64px);
}
.top-info {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 15px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
  flex-wrap: wrap;
}
.top-info span {
  margin-right: 20px;
  font-size: 14px;
  margin-bottom: 5px;
}
.search-form {
  margin-bottom: 15px;
}
.operation-buttons {
  margin-bottom: 15px;
}
.operation-buttons .el-button { padding: 6px 10px; }
.pagination-container {
  margin-top: 15px;
  text-align: right;
}

/* 移植：通知弹窗样式补充 */
.selected-users-form-item {
  margin-top: 10px;
}
.selected-count {
  margin-top: 5px;
  font-size: 12px;
  color: #666;
}

/* 移植：备注弹窗样式补充 */
::v-deep .remark-form .el-textarea {
  width: 100%;
}
::v-deep .remark-form .el-table {
  margin-top: 10px;
}

/* 补考弹窗：选中学员标签样式 */
.selected-students {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.selected-students h4 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 14px;
  color: #606266;
}

/* 试题详情样式 */
.question-detail-content {
  padding: 10px;
}
.question-item {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #eee;
}
.question-item:last-child {
  border-bottom: none;
}
.question-text {
  font-weight: 500;
  margin-bottom: 5px;
}
.options-list {
  list-style: none;
  padding-left: 20px;
  margin-bottom: 5px;
}
.options-list li {
  margin-bottom: 5px;
  cursor: default;
}
.selected {
  color: red;
  font-weight: 500;
}
.correct-opt {
  color: green;
  font-weight: 500;
}
.correct {
  color: green;
  margin-left: 10px;
}
.incorrect {
  color: red;
  margin-left: 10px;
}
.answer-info {
  margin-left: 10px;
  font-size: 14px;
  color: #666;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .operation-buttons {
    display: flex;
    flex-wrap: wrap;
  }
  .top-info {
    flex-direction: column;
  }
  .top-info span {
    margin-right: 0;
  }
}
/* 考卷详情弹窗样式 */
.exam-paper-container {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.paper-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.paper-info {
  display: flex;
  gap: 20px;
  color: #606266;
}

.questions-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.question-item {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-weight: 500;
}

.question-index {
  margin-right: 10px;
  color: #409eff;
}

.question-type {
  font-size: 13px;
  color: #67c23a;
  background-color: rgba(103, 194, 58, 0.1);
  padding: 2px 8px;
  border-radius: 12px;
  margin-left: 10px;
}

.question-content {
  margin-bottom: 10px;
  line-height: 1.6;
}

.question-options {
  margin: 10px 0 15px 20px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 5px 10px;
  border-radius: 4px;
}

.option-label {
  min-width: 20px;
  margin-right: 10px;
  font-weight: 500;
}

.correct-option {
  background-color: rgba(103, 194, 58, 0.1);
  border-left: 3px solid #67c23a;
}

.student-option {
  background-color: rgba(64, 158, 255, 0.1);
  border-left: 3px solid #409eff;
}

.question-answer {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #eee;
  font-size: 14px;
}

.answer-label {
  color: #67c23a;
  margin-bottom: 5px;
}

.student-answer {
  color: #409eff;
  margin-bottom: 5px;
}

.answer-analysis {
  color: #f56c6c;
  margin-top: 5px;
  padding: 5px 10px;
  background-color: rgba(245, 108, 108, 0.1);
  border-radius: 4px;
}
</style>
